﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using EasierRdp.Base;
using EasierRdp.Util;

namespace EasierRdp.Models
{
    class RdpServer : RdpModel
    {
        private readonly IList<RdpUserRef> _users = new List<RdpUserRef>();
        private readonly IList<RdpSession> _sessions = new List<RdpSession>();

        public const string
            AttributePort = "Port",
            ElementName = "Server";

        public IList<RdpUserRef> Users { get { return _users; } }
        public IList<RdpSession> Sessions { get { return _sessions; } }

        public int? Port { get; set; }

        public override IEnumerable<INode> Children
        {
            get
            {
                foreach (var item in _users)
                {
                    yield return item;
                }
                foreach (var item in _sessions)
                {
                    yield return item;
                }
            }
        }

        public RdpServer(string name)
        {
            Name = name;
        }

        public RdpServer(XElement element)
        {
            if (element != null)
            {
                Name = element.GetString(AttributeName);
                Id = element.GetInt(AttributeId);
                Expanded = element.GetBoolean(AttributeExpanded);
                _users.FromXml(element, RdpUserRef.ElementName);
                Port = element.GetNullableInt(AttributePort);
                return;
            }
            throw new ArgumentNullException("element");
        }

        public override XElement ToXml()
        {
            return new XElement(ElementName, Port.HasValue ? new XAttribute(AttributePort, Port) : null, new XAttribute(AttributeId, Id), new XAttribute(AttributeName, Name), new XAttribute(AttributeExpanded, Expanded), _users.ToXml());
        }

        public RdpServer Clone()
        {
            var s = (RdpServer)this.MemberwiseClone();
            s.Id = 0;
            return s;
        }
    }

    static class RdpServerExtension
    {
        public static IEnumerable<XElement> ToXml(this IEnumerable<RdpServer> src)
        {
            return src == null ? null : src.Select(s => s.ToXml());
        }

        public static void FromXml(this IList<RdpServer> src, XElement parentElement, string elementName)
        {
            foreach (var item in parentElement.Elements(elementName).Select(e => new RdpServer(e)))
            {
                src.Add(item);
            }
        }
    }
}
